<template>
  <view class="page-container">
    <HeaderBar
        position="fixed"
        title="详情"
        navBarBgc="linear-gradient(180deg, rgba(186,209,194,1) 0%, rgba(207,223,212,1) 33%, rgba(230,238,233,1) 100%);"
    ></HeaderBar>
    <view class="content-container">
      <view class="product-name">{{productName}}</view>
      <view class="visit-container flex justify-between ">
        <view class="visit-time">
          {{startDate}} {{weekDay}}   {{timeSlot}}
        </view>
        <view class="btn-back" @click="handleGoBack">返回修改</view>
      </view>
      <view class="product-list-container" v-if="crowdProductList.length >0">
        <BuyProductDetail
          v-for="(item,index) in crowdProductList"
          :key="index"
          :crowdProduct="item"
          :isShowBorderBottom="index !== crowdProductList.length - 1"
          @productNumberOperation="changeProductNumber($event,index)"
        ></BuyProductDetail>
      </view>
      <view class="tourist-container mt40">
        <view class="tip-title">需填{{handleBuyProductTotalPriceNumber().totalNumber}}位游客</view>
        <view class="tourist-info-container flex items-center " v-show="handleBuyProductTotalPriceNumber().choiceProductNumber === 1">
          <view
              v-for="(item,index) in touristInfoList"
              :key="index"
              :class="[
                  'tourist-info flex flex-col items-center justify-center',
                  item.tipContent ? 'disabled-tourist-info' : '',
                  isChoiceTourist(item) ? 'choice-tourist-info' : ''
              ]"
              @click="handleChoiceTourist(item)"
          >
            <view>{{item.name}}</view>
            <view class="red fs12">{{item.tipContent}}</view>
          </view>
          <view class="tourist-info" style="line-height: 80rpx" @click="showAddTourist = true">选择/新增></view>
        </view>
        <view
            v-for="(item,index) in crowdProductList"
            :key="index"
            :class="[
                'tourist-input-container',
                item.number ? 'tourist-input-container-border' : '',
            ]"
        >
          <template v-if="item.number" >
            <view class="choose-product-name">{{item.skuName}}</view>
            <view
                class="number-tip-container flex justify-between items-center"
            >
              <view class="number-tip flex-1" v-if="!item.touristList.length" @click.stop="choiceTourist(item)">
                需选择{{item.number}}位{{item.skuName}}
              </view>
              <view v-else class="tourist-container">
                <view
                    v-for="(touristItem,touristIndex) in item.touristList"
                    :key="touristIndex"
                    :class="[
                        'tourist-item',
                        'items-center',
                        'flex',
                    ]"
                >
                  <wd-icon name="minus-circle" size="22px" @click.stop="deleteCrowdProductTourist(index,touristIndex)"></wd-icon>
                  <view class="tourist-info pl20">
                    <view class="tourist-name">{{touristItem.name}}</view>
                    <view class="tourist-idCard">{{transferIdCardType(touristItem.idType)}}  {{touristItem.idCard}}</view>
                  </view>
                </view>
              </view>
              <wd-icon name="arrow-right" size="22px"  @click.stop="choiceTourist(item)"></wd-icon>
            </view>
          </template>
        </view>
        <view class="contact-container">
          <view class="contact-item-container flex items-center">
            <view class="label">联系人</view>
            <wd-input v-model="contactObj.contactName" placeholder="请输入联系人" :no-border="true" custom-class="custom-contact-input"/>
          </view>
          <view class="contact-item-container flex items-center mt10">
            <view class="label">联系电话</view>
            <wd-input v-model="contactObj.contactPhone" placeholder="请输入联系号码" :no-border="true" custom-class="custom-contact-input"/>
          </view>
        </view>
      </view>
      <view class="safe-area-content"></view>
    </view>
    <view class="btn-bottom-container">
      <view class="top-container flex ">
        <view class="price">￥ {{handleBuyProductTotalPriceNumber().totalPrice}}</view>
        <view class="right-container">
          <view class="price-detail-tip" @click="showDetails = !showDetails">
            <text>明细</text>
            <wd-icon name="arrow-down" size="22px" v-if="!showDetails"></wd-icon>
            <wd-icon name="arrow-up" size="22px" v-else></wd-icon>
          </view>
          <view class="btn" @click="handleCreateOrder">去支付</view>
        </view>
      </view>
      <view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
    </view>
    <AddTourist
      :showAddTourist="showAddTourist"
      :touristInfoList="touristInfoList"
      :choiceProduct="choiceProduct"
      :choiceTouristIdList="choiceTouristIdList"
      @close="handleCloseAddTourist"
      @queryTouristList="queryTouristList(false)"
    ></AddTourist>
    <!-- 明细 -->
    <wd-popup v-model="showDetails" custom-style="border-radius:12rpx;" position="bottom">
      <view style="min-height: 40vh">
        <wd-status-tip image="content" tip="暂无选择产品" v-if="!handleBuyProductTotalPriceNumber().totalNumber"/>
        <view class="pl20 pr20" v-else>
          <view
              v-for="(item,index) in crowdProductList"
              :key="index"
              v-show="item.touristList.length > 0"
              class="pt30"
          >
            <view class="flex items-center justify-between pb30">
              <text class="fw800 fs20">{{item.skuName}}</text>
              <text class="brown fw800">
                {{item.price}}￥ *
                {{item.touristList.length}}
              </text>
            </view>
            <text
                v-for="(touristItem,touristIndex) in item.touristList"
                :key="touristIndex"
                class=" pr10"
            >
              {{touristItem.name}}
            </text>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
  import {ref,getCurrentInstance} from "vue";
  import {onLoad, onPageScroll} from "@dcloudio/uni-app";
  import {toPay, touristList} from "@/api/common";
  import HeaderBar from "@/components/HeaderBar/index.vue";
  import BuyProductDetail from "@/components/BuyProductDetail/index.vue";
  import AddTourist from "@/components/AddTourist/index.vue";
  import {useMixin} from "@/hook/useMixin";
  import {createOrder} from "@/api/ticket";

  const {calculateAge,convertGender,transferIdCardType} = useMixin();
  const instance = getCurrentInstance();

  const safeInsert = ref(0);
  const showAddTourist = ref(false);
  const touristInfoList = ref([]);
  const providerId = ref("");
  const weekDay = ref("");
  const timeSlot = ref("");
  const startDate = ref("");
  const crowdProductList = ref([]);
  const choiceProduct = ref({});
  const choiceTouristIdList = ref([]);
  const stockId = ref("");
  const productName = ref("");
  const subStockId = ref("");
  const contactObj = ref({
    contactName:"张三",
    contactPhone:"18525212321"
  });
  const firstBuyProductIndex = ref(0);
  const showDetails = ref(false);
  const orderType = ref(null);

  const handleGoBack = () => {
    uni.navigateBack();
  };
  const queryTouristList = async (isShowLoad) => {
    await touristList({pageSize:99,userId:2}).then(res => {
      let {result} = res;
      if(result && result.length > 0) {
        result.forEach(item => {
          item.isChecked = false;
          item.tipContent = "";
        });
      }
      touristInfoList.value = result;
      if(isShowLoad && crowdProductList.value && crowdProductList.value.length > 0) {
        choiceProduct.value = crowdProductList.value[0];
      }
      idCardValidate();
    });
  };
  const handleBuyProductTotalPriceNumber = () => {
    let totalNumber = 0;
    let totalPrice = 0;
    let choiceProductNumber = 0;
    if(crowdProductList && crowdProductList.value.length) {
      crowdProductList.value.forEach((productItem,productIndex) => {
        totalNumber += productItem.number;
        totalPrice += productItem.number * (productItem.price ? productItem.price.toFixed(2) : 0);
        if(productItem.number) {
          if(choiceProductNumber === 0) {
            firstBuyProductIndex.value = productIndex;
          }
          choiceProductNumber += 1;
        }
      });
    }
    totalPrice = totalPrice.toFixed(2);
    return {totalNumber,totalPrice,choiceProductNumber};
  };
  const choiceTourist = (item) => {
    let {touristList} = item;
    choiceProduct.value = item;
    choiceTouristIdList.value = [];
    if(touristList && touristList.length > 0) {
      touristInfoList.value.forEach((touristItem,touristIndex) => {
        touristList.forEach(productTouristItem => {
          if(touristItem.id === productTouristItem.id) choiceTouristIdList.value.push(Number(touristItem.id));
        });
        touristItem.tipContent = ""
      });
    } else {
      touristInfoList.value.forEach((touristItem,touristIndex) => {
        touristItem.tipContent = "";
      });
    }
    showAddTourist.value = true;
    idCardValidate();
  };
  const changeProductNumber = (event,index) => {
    let {type} = event;
    switch (type) {
      case 'increment':
        crowdProductList.value[index].number += 1;
        break;
      case 'decrement':
        if(crowdProductList.value[index].number > 0) {
          if(crowdProductList.value[index].number === crowdProductList.value[index].touristList.length) {
            crowdProductList.value[index].touristList.pop();
          }
          crowdProductList.value[index].number -= 1;
        }
        break;
    }
    if(crowdProductList.value[index].number === 1) {
      console.log("entire");
      choiceProduct.value = crowdProductList.value[index];
      touristInfoList.value.forEach(touristItem => touristItem.tipContent = "");
      idCardValidate();
    }

  };
  const idCardValidate = () => {
    /*
    * ruleType
    * 0 身份证年龄校验
    * 1 身份证号码段校验
    * 2 购买频率 (后端校验)
    * 3 性别限制 (gender 1:男 2:女)
    * 4 证件类型验证
    * */
    let ruleList = choiceProduct.value.rules;
    console.log(ruleList,'ruleList');
    touristInfoList.value.forEach((touristItem,touristIndex) => {
      let {idType,idCard} = touristItem;

      if(ruleList && ruleList.length > 0) {
        ruleList.forEach(ruleItem => {
          let {ruleType,ruleContent,} = ruleItem;
          // console.log(ruleType,"ruleType");
          switch (Number(ruleType)) {
            case 4:
              // 1.校验是否满足证件类型
              let idTypeList = ruleItem.ruleContent.idTypes.split(",");
              if(idTypeList && idTypeList.length && !idTypeList.includes(idType + ""))  {
                touristInfoList.value[touristIndex].tipContent = "证件类型不符合"
              }
              break;
            case 0:
              // 2.校验是否满足年龄要求  (只校验身份证)
              let {min,max} = ruleContent;
              if(Number(idType) === 1) {
                let age = calculateAge(idCard,startDate.value);
                console.log(age,'age');
                if(age < min || age > max) {
                  console.log(age,'age-entire');
                  touristInfoList.value[touristIndex].tipContent = "年龄不符合"
                }
              }
              break;
            case 3:
              // 3. 校验证件性别 (只校验身份证)
              let {gender} = ruleContent;
              if(Number(idType) === 1) {
                let getGender = convertGender(idCard);
                if(gender != getGender) {
                  touristInfoList.value[touristIndex].tipContent = "性别不符合"
                }
              }
              break;
            case 1:
              // 3. 校验证件号段 (只校验身份证)
              if(Number(idType) === 1) {
                let {section} = ruleContent;
                let idCardFirstContentList = section.split(",");
                if(idCardFirstContentList && idCardFirstContentList.length) {
                  let isSome = idCardFirstContentList.some(prefixId => idCard.startsWith(prefixId));
                  if(!isSome) {
                    touristInfoList.value[touristIndex].tipContent = "证件归属地不符合"
                  }
                }
              }
              break;
          }
        })

      }
    })
    console.log(touristInfoList.value,'touristInfoList');
  };
  const handleCloseAddTourist = (event) => {
    let {priceId} = choiceProduct.value;
    let choiceTouristList = [];
    if(event && event.choiceTouristIdList && event.choiceTouristIdList.length > 0) {
      touristInfoList.value.forEach(touristItem => {
        event.choiceTouristIdList.forEach(id => {
          if(touristItem.id == id) {
            choiceTouristList.push(touristItem);
          }
        });
      });
      let productIndex = crowdProductList.value.findIndex(productItem => productItem.priceId == priceId);
      if(productIndex >= 0) {
        crowdProductList.value[productIndex].touristList = choiceTouristList;
      }
    }
    showAddTourist.value = false;
  };
  const deleteCrowdProductTourist = (productIndex,touristIndex) => {
    crowdProductList.value[productIndex].touristList.splice(touristIndex,1);
  };
  const isChoiceTourist = (item) => {
    return toRaw(crowdProductList.value[firstBuyProductIndex.value].touristList).some(touristItem => touristItem.id === item.id);
  };
  const handleChoiceTourist = (item) => {
    let {id} = item;
    let touristIndex = crowdProductList.value[firstBuyProductIndex.value].touristList.findIndex(touristItem => touristItem.id === id);
    if(touristIndex >= 0) {
      crowdProductList.value[firstBuyProductIndex.value].touristList.splice(touristIndex,1);
      let {number} = crowdProductList.value[firstBuyProductIndex.value].number;
      if(number > 1) crowdProductList.value[firstBuyProductIndex.value].number -= 1;
    } else {
      let {number,touristList} = crowdProductList.value[firstBuyProductIndex.value];
      console.log(number,'number');
      console.log(touristList,'touristList');
      if(number === touristList.length) {
        uni.showToast({
          icon:"none",
          title:`您只需选择${number}位游客`
        })
        return;
      }
      crowdProductList.value[firstBuyProductIndex.value].touristList.push(item);
      // if(touristList.length > number) crowdProductList.value[firstBuyProductIndex.value].number += 1;
    }

  };
  const handleCreateOrder = async () => {
    let errMessage = "";
    if(!contactObj.value.contactPhone || !contactObj.value.contactName) {
      errMessage = "请完善联系人信息";
    }
    console.log(crowdProductList.value,'crowdProductList.value');
    for (let i = 0; i < crowdProductList.value.length; i++) {
      const item = crowdProductList.value[i];
      if (item.number !== item.touristList.length) {
        errMessage = `请完善${item.skuName}产品游客信息`
        break;
      }
    }
    if(errMessage) {
      uni.showToast({
        icon: "none",
        title: errMessage
      });
      return;
    }
    let prices = [];
    crowdProductList.value.forEach(productItem => {
      let {touristList,priceId,number} = productItem;
      console.log(toRaw(touristList),'touristList');
      if(toRaw(touristList) && toRaw(touristList).length > 0) {
        let productInfo = {};
        let realnames = [];
        productInfo.priceId = priceId;
        productInfo.num = number;
        toRaw(touristList).forEach(touristItem => {
          let {name,idType,idCard,tel} = touristItem;
          realnames.push({
            name,
            idType,
            idCard,
            tel
          });
        });
        productInfo.realnames = realnames;
        prices.push(productInfo);
      }
    });
    console.log(prices,'prices');
    await createOrder({
      merchantId:providerId.value,
      playDate:startDate.value,
      stockId:stockId.value,
      subStockId:subStockId.value,
      contactName:contactObj.value.contactName,
      contactPhone:contactObj.value.contactPhone,
      prices,
      // #ifdef APP
      source:1,
      // #endif
      // #ifdef MP-WEIXIN
      source:0,
      // #endif
    }).then(res => {
      let { orderId, orderType: _orderType } = res.result;
      orderType.value = _orderType;
      handleToPay(orderId);
    });
  };
  const handleToPay = async (id) => {
    await toPay({type:"jsapi",id}).then(res => {
      let { appId,nonceStr, packageValue,paySign,signType,timeStamp } = res.result;
      uni.navigateTo({
        url:`/ticketSubPack/pages/PaymentOrder/index?totalPrice=${handleBuyProductTotalPriceNumber().totalPrice}&timeStamp=${timeStamp}&nonceStr=${nonceStr}&packageValue=${encodeURIComponent(packageValue)}&signType=${signType}&paySign=${encodeURIComponent(paySign)}&orderId=${id}&orderType=${orderType.value}`
      })
    });
  };

  onPageScroll(() => {})
  onShow(async() => {
    await queryTouristList(true);
  });
  onLoad((options) => {
    console.log(options,'options');
    safeInsert.value = uni.getSystemInfoSync().safeAreaInsets.bottom;
    let {
      startDate:_startDate,
      timeSlot:_timeSlot,
      weekDay:_weekDay,
      providerId:_providerId,
      stockId:_stockId,
      subStockId:_subStockId,
      productName:_productName,
    } = options;
    startDate.value = _startDate;
    timeSlot.value = _timeSlot;
    weekDay.value = _weekDay;
    providerId.value = _providerId;
    stockId.value = _stockId;
    subStockId.value = _subStockId;
    productName.value = _productName;
    crowdProductList.value = uni.getStorageSync("reservationProductList");
    crowdProductList.value.forEach(crowdProductItem => {
      crowdProductItem.touristList = [];
    })
    console.log(crowdProductList,'crowdProductList');
  });

</script>

<style lang="scss" scoped>
  .page-container {
    .content-container {
      padding: 20rpx 27.5rpx;
      width: auto;
      min-height: 100vh;
      background: linear-gradient(180deg, rgba(228, 237, 231, 1) 0%, rgba(238, 239, 231, 1) 18%, rgba(238, 239, 231, 1) 100%);
      .product-name {
        font-size: 41.5rpx;
        font-weight: bold;
      }
      .visit-container {
        padding: 26.5rpx 0 80rpx 0;
        .visit-time {
          font-size: 25rpx;
          color: #2B2B24;
        }
        .btn-back {
          font-size: 25rpx;
          padding: 2rpx;
          border-radius: 10.5rpx;
          border: 1px solid #26704E;
          color: #000000;
        }
      }
      .product-list-container {
        padding: 0 32.5rpx;
        border-radius: 10.5rpx;
        background: #FFFFFF;
      }
      .tourist-container {
        padding: 46rpx 32rpx  20rpx 32rpx;
        border-radius: 10.5rpx;
        background: #FFFFFF;
        .tip-title {
          font-size: 33.5rpx;
          font-weight: bold;
        }
        .tourist-info-container {
          padding: 30rpx 0 50rpx 0;
          flex-wrap: wrap;
          .tourist-info {
            height: 80rpx;
            font-size: 25rpx;
            border-radius: 10.5rpx;
            border: 1rpx solid #1B9C61;
            padding: 0 30rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            text-align: center;
          }
          .disabled-tourist-info {
            background: #f2f2f3;
            border: 0;
          }
          .choice-tourist-info {
            color: #ffffff;
            background: #1B9C61;
          }
        }
        .tourist-input-container {
          .choose-product-name {
            padding-top: 30rpx;
            font-size: 29rpx;
            font-weight: bold;
          }
          .number-tip-container {
            .number-tip {
              padding-bottom: 30rpx;
              padding-top: 22.5rpx;
              font-size: 25rpx;
              color: #D33700;
            }
            .tourist-container {
              flex: 1;
              .tourist-item {
                border-bottom: 1rpx solid #cccccc;
                margin-bottom: 20rpx;
                padding-bottom: 20rpx;
                .tourist-info {
                  .tourist-name {
                    font-weight: bold;
                    font-size: 29rpx;
                    padding-bottom: 10rpx;
                  }
                  .tourist-idCard {
                    font-size: 25rpx;
                  }
                }
              }
              .tourist-item:last-child {
                border-bottom: 0;
                margin-bottom: 0;
                padding-bottom: 0;
              }
            }
          }
        }
        .tourist-input-container-border {
          border-bottom: 1rpx solid #C0C2B3;
        }
        .contact-container {
          margin-top: 55rpx;
          padding: 15.5rpx;
          font-size: 25rpx;
          border-radius: 10.5rpx;
          background:#EEEFE7;
          .contact-item-container {
            .label {
              width: 14vw;
            }
            ::v-deep.custom-contact-input {
              flex: 1;
              background: #EEEFE7 !important;
            }
          }
        }
      }
      .safe-area-content {
        height: 200rpx;
      }
    }
    .btn-bottom-container {
      position: fixed;
      width: 100%;
      bottom: 0;
      left: 0;
      z-index:99;
      background: #fdffeb;
      .top-container {
        justify-content: space-between;
        align-items: center;
        padding: 32rpx 20rpx 0 59rpx;
        .price {
          font-size: 42rpx;
          font-weight: bold;
          color: #AA5413;
        }
        .right-container {
          display: flex;
          align-items: center;
          .price-detail-tip {
            display: flex;
            align-items: center;
            padding-right: 11rpx;
            text {
              font-size: 30rpx;
            }
          }
          .btn {
            border-radius: 10.5rpx;
            font-weight: bold;
            padding: 25rpx 32rpx;
            color: #FDFFEB;
            background: #AA5413;
          }
        }
      }
    }
  }
</style>
